package com.javaweb.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/30 8:54
 */

@RestController
@RequestMapping("/web")
@Slf4j
public class WebObjectController {

//    @RequestMapping(value = "/req",
//            method = RequestMethod.GET)
    @GetMapping("/req")
    public String getRequest(HttpServletRequest request,
                             Model model,
                             HttpServletResponse response) {
        log.info("request: {}", request);
        log.info("request user-agent: {}",
                request.getHeader("User-Agent")) ;
        log.info("request url: {}", request.getRequestURI()) ;
        return "ok" ;
    }


    @GetMapping("/session")  // web/session
    public String getSession(HttpSession session) {

        log.info("session id : {}", session.getId()) ;
        // sava data in session
        session.setAttribute("name", "zhangsan");
        return "ok" ;
    }

    @GetMapping("/session/further")
    public String getFurther(HttpSession session) {
        log.info("session id : {}", session.getId()) ;
        log.info("data from session: {}", session.getAttribute("name")) ;
        return "ok" ;
    }
    @GetMapping("/cookie")
    public String getCookie(HttpServletResponse resp) {
        // 存储 cookie
        Cookie cookie = new Cookie("cookie_key", "cookie_value");
        cookie.setMaxAge(60);
        resp.addCookie(cookie);
        return "ok" ;
    }

    @GetMapping("/cookie/further")
    public String getFurtherCookie(HttpServletRequest request) {
        //获取cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("cookie_key"))
                log.info("cookie name:{} ", cookie.getName()) ;
                log.info("cookie value: {}", cookie.getValue()) ;
        }

        return "ok" ;
    }






}
